package com.mmall.common.util;

import com.mmall.common.base.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * @author gg
 * @version ErrorUtil.java, v 0.1 2019-05-14 10:44 gg
 */
@Slf4j
public class ErrorUtil {

    private static ServerResponse getParamErrorMessage(MethodArgumentNotValidException e) {
        //按需重新封装需要返回的错误信息
        StringBuilder stringBuilder = new StringBuilder();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，错误信息
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            if (stringBuilder.length() > 1) {
                stringBuilder.append(";  ");
            }
            stringBuilder.append(error.getDefaultMessage());
        }
        return ServerResponse.createByErrorCodeMessage(1, stringBuilder.toString());
    }

    public static ServerResponse handException(Exception ex) {
        try {
            log.error("admin error:{}", ex);
            throw ex;
        } catch (MethodArgumentNotValidException e) {
            return getParamErrorMessage(e);
        } catch (HttpRequestMethodNotSupportedException e) {
            return ServerResponse.createByErrorCodeMessage(405, "请求方式错误");
        } catch (IllegalArgumentException e) {
            return ServerResponse.createByErrorCodeMessage(400, e.getMessage());
        } catch (RuntimeException e) {
            return ServerResponse.createByErrorCodeMessage(500, e.getMessage());
        } catch (BindException e) {
            return ServerResponse.createByErrorCodeMessage(1, e.getAllErrors().get(0).getDefaultMessage());
        } catch (Exception e) {
            return ServerResponse.createByErrorCodeMessage(1, "系统异常");
        }
    }
}